package com.android.jianboshi.manager;

import static android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_LATENCY;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.android.baselibrary.tool.Log;
import com.android.baselibrary.tool.SPUtil;
import com.android.jianboshi.MyApplication;
import com.android.jianboshi.bean.BtParseInfo;
import com.android.jianboshi.constants.SPConstants;
import com.blankj.utilcode.util.ConvertUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.crypto.Mac;

import cn.wandersnail.commons.util.StringUtils;

public class BluetoothHelper {

    public interface BroadCastCallback {

        void onReceiverData(ScanResult result);

    }

    private BroadCastCallback broadCastCallback;

    public void setBroadCastCallback(BroadCastCallback broadCastCallback) {
        this.broadCastCallback = broadCastCallback;
    }

    private static final String TAG = "test";
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBLEScanner;
    private ScanSettings mScanSettings;

    // 不同版本回调写法不一样
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    private ScanCallback mScanCallback;
    private boolean mScanning = false;

    Handler handler = new Handler();

    public BluetoothHelper() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    /**
     * 打开蓝牙
     *
     * @return
     */
    public boolean open() {
        return mBluetoothAdapter != null && mBluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF && mBluetoothAdapter.enable();
    }

    /**
     * 关闭蓝牙
     *
     * @return
     */
    public boolean close() {
        return isOpen() && mBluetoothAdapter.disable();
    }

    /**
     * 是否打开蓝牙
     *
     * @return
     */
    public boolean isOpen() {
        return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();
    }

    public void scan() {
        //如果没打开蓝牙，不进行扫描操作，或请求打开蓝牙。
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            return;
        }
        //处于未扫描的状态
        Log.i("开始扫描:" + mScanning);
        if (!mScanning) {
            //android 5.0后
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //标记当前的为扫描状态
                mScanning = true;
                //获取5.0新添的扫描类
                if (mBLEScanner == null) {
                    //mBLEScanner是5.0新添加的扫描类，通过BluetoothAdapter实例获取。
                    mBLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                }
                mScanSettings = getScanSettings();
                mScanCallback = getScanCallback();

                //开始扫描
                ScanFilter.Builder builder = new ScanFilter.Builder();
//                builder.setDeviceName("GYMSTR");
                //mScanSettings是ScanSettings实例，mScanCallback是ScanCallback实例，后面进行讲解。
                ScanFilter filter = builder.build();

                mBLEScanner.startScan(Arrays.asList(filter), mScanSettings, mScanCallback);
            } else {
                mLeScanCallback = getLeScanCallback();
                //标记当前的为扫描状态
                mScanning = true;
                //5.0以下  开始扫描
                //mLeScanCallback是BluetoothAdapter.LeScanCallback实例
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            }
            handler.postDelayed(runnable, 30 * 1000);

        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            stopScan();
            scan();
        }
    };

    public void release() {
        stopScan();
        handler.removeCallbacks(runnable);
    }

    public void stopScan() {
        //停止扫描设备
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //标记当前的为未扫描状态
            mScanning = false;
            mBLEScanner.stopScan(mScanCallback);
        } else {
            //标记当前的为未扫描状态
            mScanning = false;
            //5.0以下  停止扫描
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        Log.i("停止扫描");
    }

    private BluetoothAdapter.LeScanCallback getLeScanCallback() {
        if (mLeScanCallback == null) {
            //5.0以下版本
            mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                    //对扫描到的设备进行操作。如：获取设备信息。
                    BtParseInfo btParseInfo = new BtParseInfo(scanRecord);
                }
            };
        }
        return mLeScanCallback;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private ScanCallback getScanCallback() {

        // 5.0及以上版本
        if (mScanCallback == null) {
            mScanCallback = new ScanCallback() {
                //当一个蓝牙ble广播被发现时回调
                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    super.onScanResult(callbackType, result);
                    //扫描类型有开始扫描时传入的ScanSettings相关
                    //对扫描到的设备进行操作。如：获取设备信息。

//                    Log.i("收到数据:"+ result.getDevice().getType() + " "+ ConvertUtils.bytes2HexString(result.getScanRecord().getBytes()));
                    //0709 47594D535452 08 CA    00 0235 0081 45 00
                    //0709 47594D535452 09 CA D4 00 0231 006C 1E 00
                    //11FF 5CCAD39724CE 09 CA 06 00 003A 0099 29 00
//                    byte begin = result.getScanRecord().getBytes()[0];
//                    if(begin==(byte)0x08)
//                    {
//
//                    }
                    if (broadCastCallback != null) {
//                        broadCastCallback.onReceiverData(result.getScanRecord().getBytes());
                        broadCastCallback.onReceiverData(result);

                    }

//                    String Mac = SPUtil.getStringValue(MyApplication.context, SPConstants.Mac, "");
//                    if (!TextUtils.isEmpty(Mac)) {
//                        if (Mac.equals(result.getDevice().getAddress())) {
//                            if (broadCastCallback != null) {
//                                broadCastCallback.onReceiverData(result.getScanRecord().getBytes());
//                            }
//                        }
//                    } else {
//                        if (broadCastCallback != null) {
//                            broadCastCallback.onReceiverData(result.getScanRecord().getBytes());
//                        }
//                    }
                }

                //批量返回扫描结果
                //@param results 以前扫描到的扫描结果列表。
                @Override
                public void onBatchScanResults(List<ScanResult> results) {
                    super.onBatchScanResults(results);
                }

                //当扫描不能开启时回调
                @Override
                public void onScanFailed(int errorCode) {
                    super.onScanFailed(errorCode);
                    //扫描太频繁会返回ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED，表示app无法注册，无法开始扫描。
                    Log.d("test", "onScanFailed:" + errorCode);
                }


            };
        }
        return mScanCallback;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private ScanSettings getScanSettings() {
        // 5.0及以上版本
        if (mScanSettings == null) {
            //创建ScanSettings的build对象用于设置参数
            ScanSettings.Builder builder = new ScanSettings.Builder()
                    //设置高功耗模式
                    .setScanMode(SCAN_MODE_LOW_LATENCY);
            //android 6.0添加设置回调类型、匹配模式等
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //定义回调类型
                builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
                //设置蓝牙LE扫描滤波器硬件匹配的匹配模式
                builder.setMatchMode(ScanSettings.MATCH_MODE_STICKY);
            }
            //芯片组支持批处理芯片上的扫描
            if (mBluetoothAdapter.isOffloadedScanBatchingSupported()) {
                //设置蓝牙LE扫描的报告延迟的时间（以毫秒为单位）
                //设置为0以立即通知结果
                builder.setReportDelay(0L);
            }
            mScanSettings = builder.build();
        }
        return mScanSettings;
    }

    //模拟假数据
    public void initData() {
        //08CA000223 0064 10 64
        List<String> dataList = new ArrayList<>();
        //按压
        dataList.add("070947594D53545209CAD4000231006C1E00");
        dataList.add("070947594D53545209CAD4000231006C1E00");
        dataList.add("070947594D53545209CAD4000231006C1E00");
        dataList.add("070947594D53545209CACF00023100761C00");
        dataList.add("070947594D53545209CACF00023100761C00");
        dataList.add("070947594D53545209CAB700023100311300");
        dataList.add("070947594D53545209CAB700023100311300");

        for (String data : dataList) {
            byte[] bytes = ConvertUtils.hexString2Bytes(data);
//            broadCastCallback.onReceiverData(bytes);
//            SystemClock.sleep(50);

        }
    }

}

